package cn.fz.wsdemo.config;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.MapUtils;
import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Map;
import java.util.Set;

@Slf4j
@Component
public class SecurityUserDetailsService implements UserDetailsService {
    @Autowired
    private SqlSession sqlSession;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        try {
            Map<String, Object> userinfoMap = sqlSession.selectOne("Login.loadUserByUsername", username);
            SecurityUserDetails user = SecurityUserDetails.builder()
                    .username(username)
                    .nickname(MapUtils.getString(userinfoMap, "nick_name"))
                    .password(MapUtils.getString(userinfoMap, "bcrypt_passwd"))
                    .authorities((Set<GrantedAuthority>) new ArrayList<GrantedAuthority>())
                    .accountNonExpired(true)
                    .accountNonLocked(true)
                    .credentialsNonExpired(true)
                    .enabled(true)
                    .build();

            log.info("登录用户信息：{}", user);
            return user;
        } catch (Exception e) {
            String msg = "Username: " + username + " not found";
            log.error(msg, e);
            throw new UsernameNotFoundException(msg);
        }
    }
}
